package com.chalk.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.security.JwtRedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @date: 2019-04-01 下午 06:58
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
public class JwtUserLoginAuthFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private JwtRedisUtil jwtRedisUtil;

    public JwtUserLoginAuthFilter(AuthenticationManager authenticationManager, JwtRedisUtil jwtRedisUtil) {
        this.authenticationManager = authenticationManager;
        this.jwtRedisUtil = jwtRedisUtil;
        super.setFilterProcessesUrl("/auth/login");
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password, new ArrayList<>()));
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {

        // 查看源代码会发现调用getPrincipal()方法会返回一个实现了`UserDetails`接口的对象
        // 所以就是JwtUser啦
        User user = (User) authResult.getPrincipal();
        String role = "";
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }
        // 返回创建成功的token
        String token = jwtRedisUtil.createRedisToken(user.getUsername(), role);
        // 返回创建成功的刷新 refreshToken
        String refreshToken = jwtRedisUtil.createRefreshToken(user.getUsername());
        // 按照jwt的规定，最后请求的格式应该是 `bearer token`
        response.setContentType("application/json;charset=utf-8");
        Map<String ,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("refresh", refreshToken);
        response.getWriter().write(JSONObject.toJSONString(Result.success(ResultCode.SUCCESS.msg(), map)));
    }

    // 这是验证失败时候调用的方法
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail(ResultCode.AUTH_FAIL.msg())));
    }
}
